package com.flong.config;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import com.flong.mapper.ICronMapper;

/**
 * @Description 根据数据库实行动态定时器任务. 
 * 
 * https://www.cnblogs.com/je-ge/p/6129667.html
 * http://www.jb51.net/article/126569.htm
 * http://blog.csdn.net/LJY_SUPER/article/details/74331447
 * 
 * @ClassName CompleteScheduleConfig
 * @Date 2018年2月24日 下午2:00:54
 * @Author liangjl
 * @Copyright (c) All Rights Reserved, 2018.
 */
@Component
@Configuration
@EnableScheduling
public class TaskScheduleConfig implements SchedulingConfigurer {
	private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	private static final String DEFAULT_CRON = "0/5 * * * * ?"; // 设置一个默认值,表示每秒进行执行一次
	private String cron = DEFAULT_CRON;
	private @Autowired ICronMapper cronMapper;
	
	
	public String getCron() {
		return this.cron;
	}

	public void setCron(String cron) {
		this.cron = cron;
	}
	
	
 
	/**
	 * 执行定时任务.
	 */
	
 	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
 		
 		/**====================方法1====================**/
 		
		 /*taskRegistrar.addTriggerTask(
			// 1.添加任务内容(Runnable)
			() ->System.out.println("动态修改定时任务cron参数，当前时间：" + dateFormat.format(new Date())),
			
			// 2.设置执行周期(Trigger)
			triggerContext -> {
				// 2.1 从数据库获取执行周期
				cron = cronMapper.getCron();
				// 2.2 合法性校验.
				if (StringUtils.isEmpty(cron)) {
					// Omitted Code ..
					System.out.println("cron表达式为空");
				} else {
					// TODO 处理其他事情
					System.out.println("cron表达式不为空");
				}
				// 2.3 返回执行周期(Date)
				return new CronTrigger(cron).nextExecutionTime(triggerContext);
			}); 
 		*/
 		
 		
 		/**====================方法2====================**/
	

	 
	/*	@Override
		public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
			taskRegistrar.addTriggerTask(new Runnable() {
				@Override
				public void run() {
					if (!cron.equals(DEFAULT_CRON)) {
					}
					// 定时任务的业务逻辑
					System.out.println("动态修改定时任务cron参数，当前时间：" + dateFormat.format(new Date()));
				}
			}, new Trigger() {
				@Override
				public Date nextExecutionTime(TriggerContext triggerContext) {
					// 定时任务触发，可修改定时任务的执行周期
					return new CronTrigger(cron).nextExecutionTime(triggerContext);
				}
			});
		}
	*/
 	
 		
 	}
 	

}